#include "common.c"

void loop(int listener) {
    static char buf[1024];
    
    int sock = accept(listener, 0, 0);
    if (sock < 0) {
        perror("accept");
        exit(1);
    }
    while (1) {
        ssize_t r = recv(sock, buf, sizeof(buf), 0);
        if (r <= 0 || !send_all(sock, buf, r)) {
            break;
        }
    }
    close(sock);
}

int main() {
    struct sockaddr_in addr;
    
    int listener = socket(AF_INET, SOCK_STREAM, 0);
    if (listener < 0) {
        perror("socket");
        return 1;
    }
    
    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(12345);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    
    if (bind(listener, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind");
        return 1;
    }
    
    if (listen(listener, 10) < 0) {
        perror("listen");
        return 1;
    }
    while (1) loop(listener);
}
